package com.kehutong.common.urlconfig;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.coraframework.http.HttpClient;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONObject;
import org.coraframework.util.CallBack;

/**
 * 文件服务器相关配置
 * @author liuzhen
 */
@Singleton
public class FileUrlConfig extends UrlConfig{

	protected FileUrlConfig() {
		super("web", "file_url");
	}
	
	public InputStream download(String fileId) throws Exception {
		try {
			final byte[] bytes = download("/file/download", http->{
				http.addParam("id", fileId);
			});
			return new ByteArrayInputStream(bytes);
		} catch (IOException e) {
			return null;
		}
	}

	public byte[] download(String page, CallBack<HttpClient> clientCallBack) throws Exception {
		final HttpClient httpClient = HttpClient.create(url + page);
		clientCallBack.call(httpClient);

		return httpClient.download();
	}


	public String getFile(String fileId) {
		return getFile(fileId, false);
	}

    public String getFile(String fileId, boolean isBig) {
        StringBuilder sb = new StringBuilder().append(this.url)
                .append("/file/show/")
                .append(fileId);
        if (isBig) {
            sb.append("?isBig=true");
        }
        return sb.toString();
    }

	public String getVideo(String fileId) {
		StringBuilder sb = new StringBuilder().append(this.url)
				.append("/file/vidoe/")
				.append(fileId);
		return sb.toString();
	}

	/**
	 * post请求,返回json
	 * @param page
	 * @param client
	 * @return
	 * @throws Exception
	 */
	public JSONObject post(String page, CallBack<HttpClient> client) throws Exception {
		final HttpClient httpClient = HttpClient.create(getUrl() + page);
		client.call(httpClient);

		String text = httpClient.post();
		if (httpClient.getResponseCode() != 200) {
			return httpError(httpClient.getResponseCode(), "http状态错误");
		}

		return JSON.parseObject(text);
	}

	/**
	 * post请求,返回json
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public JSONObject sendFile(File file, CallBack<HttpClient> client) throws Exception {
		final HttpClient httpClient = HttpClient.create(getUrl() + "/file/upload");
		client.call(httpClient);
		String text = httpClient.sendFile(file);
		if (httpClient.getResponseCode() != 200) {
			return httpError(httpClient.getResponseCode(), "http状态错误");
		}

		return JSON.parseObject(text);
	}
}
